const prefix = 'animate__'
const animateStatus = {
  // 动画状态
  isStop: false, // 当isStop为true时, 动画会被停止
}
/**
 * 运行动画
 * @param {*} $el dom对象
 * @param {*} animations 动画序列
 * @param {*} options
 * @param {Component} component
 * @returns
 */
export async function runAnimation($el, animations = [], options = {}, component) {
  animateStatus.isStop = false
  return new Promise(async (res) => {
    if (animations.find((animation) => animation.pending)) {
      return false
    }
    const play = (animation) =>
      new Promise((resolve) => {
        animation.pending = true
        const classList = [`${prefix}${animation.value}`, `${prefix}animated`]

        $el.classList.add(...classList)
        console.log($el, animation, animateStatus.isStop)
        const removeAnimation = () => {
          console.log('animationend')
          $el.removeEventListener('animationend', removeAnimation)
          $el.removeEventListener('animationcancel', removeAnimation)
          $el.classList.remove(...classList)
          animation.pending = false
          if (component && animation.value.indexOf('Out') > -1) {
            component.isShow = false
          }
          console.log(component)
          clearInterval(timer)
          resolve(component)
        }
        const timer = setInterval(() => {
          console.log(options.isEnabledStop, animateStatus.isStop)
          if (options.isEnabledStop && animateStatus.isStop) {
            $el.removeEventListener('animationend', removeAnimation)
            $el.removeEventListener('animationcancel', removeAnimation)
            $el.classList.remove(...classList)
            animation.pending = false
            clearInterval(timer)
            animateStatus.isStop = false
            res()
          }
        }, 30)

        $el.addEventListener('animationend', removeAnimation)
        $el.addEventListener('animationcancel', removeAnimation)
      })

    for (let i = 0, len = animations.length; i < len; i++) {
      const animation = animations[i]
      if (animation.value && animation.value.length) {
        await play(animations[i])
      }
    }

    animateStatus.isStop = false
    res()
  })
}

/**
 * 停止组件的动画
 * @param { Component } component
 */
export function stopAnimateByComponent(component) {
  animateStatus.isStop = true
  const { key, animations } = component
  const id = `c-wrap-${key}`
  const classList = [`${prefix}animated`]
  animations.list.forEach((animation) => {
    classList.push(animation.value)
    animation.pending = false
  })
  document.getElementById(id)?.classList.remove(...classList)
}
